package com.javaio.demo.socket;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 */
public class Server {

    public static void main(String[] args) {
        final int PROT = 8888;
        final String TUICHU = "t";
        //服务端ServerSocket
        ServerSocket serverSocket = null;
        try {
            //服务器绑定监听端口 (监听端口有没有被客户端连接)
            serverSocket = new ServerSocket(PROT);
            System.out.println("==== 启动服务器 监听端口 ====" + PROT);

            //循环等待客户端连接  --阻塞->accept
            while (true) {
                //socket是请求客户端连接的时候产生的也表示客户端socket  accept阻塞 直到客户端连接请求
                Socket socket = serverSocket.accept();
                System.out.println("==== 客户端端口 ====" + socket.getPort());
                //流里面的装饰器模式
                //进行构造输入
                //服务器读入客户端数据BufferedReader
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream())
                );
                //进行构造输出
                //服务器向客服端发送数据 BufferedWriter
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                );

                String msg = null;
                while ((msg = reader.readLine()) != null) {
                    //进行客户端发送的消息读取
                    System.out.println("客户端口" + socket.getPort() + "消息" + msg);
                    //发送消息到客户端
                    writer.write( msg + "\n");
                    //缓冲区 保证是用的BufferedReader  避免资源消费过多
                    writer.flush();
                    if (TUICHU.equals(msg)) {
                        System.out.println("关闭");
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != serverSocket) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭异常");
                    e.printStackTrace();
                }
            }
        }

    }
}